<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>协程 - Oatpp教程</title>
        <!-- Custom HTML head -->
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">
        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">
        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script>
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script>
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script>
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script>
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="DTO.html"><strong aria-hidden="true">1.</strong> DTO</a></li><li class="chapter-item expanded "><a href="Async概述.html"><strong aria-hidden="true">2.</strong> Async</a></li><li class="chapter-item expanded "><a href="Simple_vs_Async.html"><strong aria-hidden="true">3.</strong> Simple vs Async</a></li><li class="chapter-item expanded "><a href="协程.html" class="active"><strong aria-hidden="true">4.</strong> 协程</a></li><li class="chapter-item expanded "><a href="关系型对象映射框架.html"><strong aria-hidden="true">5.</strong> ORM</a></li><li class="chapter-item expanded "><a href="Monolithization.html"><strong aria-hidden="true">6.</strong> Monolithization</a></li><li class="chapter-item expanded "><a href="步骤指南.html"><strong aria-hidden="true">7.</strong> 步骤指南</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Oatpp教程</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script>
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="协程"><a class="header" href="#协程">协程</a></h1>
<p>Oat++的协程非传统意义上的协程</p>
<p>Oat++采用自定义无状态的协程调度，这种调度提供了额外的优化空间和更好的利用CPU资源</p>
<p>Oat++是通过<code>oatpp::async::Executor</code> 来执行协程的。在一些迭代中，协程会返回<code>oatpp::async::Action</code> 去告诉执行者下一步要做什么。通过这种方式，Oat++ Async  processor重新调度协程去完成相关工作。</p>
<h2 id="async-executor"><a class="header" href="#async-executor">Async Executor</a></h2>
<p><code>oatpp::async::Executor</code> 分配三个工作组，通过设置数字来为每一个工作组指定线程数量</p>
<pre><code class="language-text-x-c-src">oatpp::async::Executor executor(
    1 /* data-processing workers */, 
    1 /* I/O workers */, 
    1 /* timer workers */
);
</code></pre>
<p>所有的协程初始化是通过 data-processing 工作组，可能会重新调度IO或定时器，这些都取决于<code>oatpp::async::Action</code> 返回的协程迭代器</p>
<p><img src="%E5%8D%8F%E7%A8%8B/image.png" alt="" /></p>
<blockquote>
<p>虽然Oat++ 异步处理器会重新调度协程到不同的线程中，但是协程的创建和销毁是在同一个线程中的</p>
</blockquote>
<h3 id="io-worker"><a class="header" href="#io-worker">I/O Worker</a></h3>
<p>对于I/O <code>oatpp::async::Executor</code> 采用基于事件IO的实现<code>IOEventWorker</code></p>
<ul>
<li>Mac/BSD系统采用基于kqueue的实现</li>
<li>Linux系统采用基于epoll的实现</li>
</ul>
<p>当协程返回的Action类型为TYPE_IO_WAIT，在kqueue/epoll中将重新分配I/O worker的文件描述符</p>
<p>因此OAT++不会浪费CPU的资源在快速轮询的长等待连接上。</p>
<h3 id="api"><a class="header" href="#api">API</a></h3>
<p>在Oatpp中，协程是从<code>oatpp::async::Coroutine</code>或<code>oatpp::async::CoroutineWithResult</code>中继承而来</p>
<p>协程在<code>oatpp::async::Executor</code> 中被处理</p>
<pre><code class="language-text-x-c-src">class MyCoroutine : public oatpp::async::Coroutine&lt;MyCoroutine&gt; {
public:

  //act() : 是协程返回Action的入口，用来告诉worker下一步要干嘛
  Action act() override {
    OATPP_LOGD(&quot;MyCoroutine&quot;, &quot;act()&quot;);
    return yieldTo(&amp;MyCoroutine::step2);
  }

  Action step2() {
    OATPP_LOGD(&quot;MyCoroutine&quot;, &quot;step2&quot;);
    return yieldTo(&amp;MyCoroutine::step3);
  }

  Action step3() {
    OATPP_LOGD(&quot;MyCoroutine&quot;, &quot;step3&quot;);
    return finish();
  }

};

oatpp::async::Executor executor();

executor.execute&lt;MyCoroutine&gt;();

executor.waitTasksFinished();
executor.stop();
executor.join();
</code></pre>
<p>输出为：</p>
<pre><code class="language-text-plain">MyCoroutine:act()
MyCoroutine:step2
MyCoroutine:step3
</code></pre>
<h3 id="从协程中调用协程"><a class="header" href="#从协程中调用协程">从协程中调用协程</a></h3>
<pre><code class="language-text-x-c-src">class OtherCoroutine : public oatpp::async::Coroutine&lt;OtherCoroutine&gt; {
public:
  Action act() override {
    OATPP_LOGD(&quot;OtherCoroutine&quot;, &quot;act()&quot;);
    return finish();
  }
};

class MyCoroutine : public oatpp::async::Coroutine&lt;MyCoroutine&gt; {
public:
  Action act() override {
    OATPP_LOGD(&quot;MyCoroutine&quot;, &quot;act()&quot;);
    return OtherCoroutine::start().next(finish());
    //Action将会在OtherCoroutine后被执行
    );
  }
};

oatpp::async::Executor executor();

executor.execute&lt;MyCoroutine&gt;();

executor.waitTasksFinished();
executor.stop();
executor.join();
</code></pre>
<p>输出：</p>
<pre><code class="language-text-x-c-src">MyCoroutine:act()
OtherCoroutine:act()
</code></pre>
<h3 id="调用协程并且返回结果"><a class="header" href="#调用协程并且返回结果">调用协程并且返回结果</a></h3>
<pre><code class="language-text-x-c-src">class CoroutineWithResult : 
	public oatpp::async::CoroutineWithResult&lt;CoroutineWithResult, const char* /*结果类型*/&gt; 
{
public:
  Action act() override {
    OATPP_LOGD(&quot;CoroutineWithResult&quot;, &quot;act()&quot;);
    return _return(&quot;&lt;result&gt;&quot;);
  }
};

class MyCoroutine : public oatpp::async::Coroutine&lt;MyCoroutine&gt; {
public:
  Action act() override {
    OATPP_LOGD(&quot;MyCoroutine&quot;, &quot;act()&quot;);
    return CoroutineWithResult::startForResult().callbackTo(&amp;MyCoroutine::onResult);
  }

  Action onResult(const char* result) {
    OATPP_LOGD(&quot;MyCoroutine&quot;, &quot;result='%s'&quot;, result);
    return finish();
  }
};

oatpp::async::Executor executor();

executor.execute&lt;MyCoroutine&gt;();

executor.waitTasksFinished();
executor.stop();
executor.join();
</code></pre>
<p>输出：</p>
<pre><code class="language-text-plain">MyCoroutine:act()
CoroutineWithResult:act()
MyCoroutine:result='&lt;result&gt;'
</code></pre>
<h3 id="计数器"><a class="header" href="#计数器">计数器</a></h3>
<pre><code class="language-text-x-c-src">class MyCoroutineCounter : public oatpp::async::Coroutine&lt;MyCoroutineCounter&gt; {
private:
  const char* m_name;
  v_int32 m_counter = 0;
public:
  MyCoroutineCounter(const char* name) : m_name(name) {}

  Action act() override {
    OATPP_LOGD(m_name, &quot;counter=%d&quot;, m_counter);
    if(m_counter &lt; 10) {
      m_counter ++;
      return repeat();
    }
    return finish();
  }

};

oatpp::async::Executor executor();

executor.execute&lt;MyCoroutineCounter&gt;(&quot;A&quot;);
executor.execute&lt;MyCoroutineCounter&gt;(&quot;B&quot;);
executor.execute&lt;MyCoroutineCounter&gt;(&quot;C&quot;);

executor.waitTasksFinished();
executor.stop();
executor.join();
</code></pre>
<p>一个可能的输出</p>
<pre><code class="language-text-plain">A:counter=0
B:counter=0
C:counter=0
A:counter=1
B:counter=1
C:counter=1
A:counter=2
B:counter=2
C:counter=2
A:counter=3
B:counter=3
C:counter=3
A:counter=4
B:counter=4
C:counter=4
A:counter=5
B:counter=5
C:counter=5
A:counter=6
B:counter=6
C:counter=6
A:counter=7
B:counter=7
C:counter=7
A:counter=8
B:counter=8
C:counter=8
A:counter=9
B:counter=9
C:counter=9
A:counter=10
B:counter=10
C:counter=10
</code></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="Simple_vs_Async.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                            <a rel="next" href="关系型对象映射框架.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="Simple_vs_Async.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                    <a rel="next" href="关系型对象映射框架.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>

        <!-- Livereload script (if served using the cli tool) -->
        <script>
            const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsAddress = wsProtocol + "//" + location.host + "/" + "__livereload";
            const socket = new WebSocket(wsAddress);
            socket.onmessage = function (event) {
                if (event.data === "reload") {
                    socket.close();
                    location.reload();
                }
            };

            window.onbeforeunload = function() {
                socket.close();
            }
        </script>
        <script>
            window.playground_copyable = true;
        </script>
        <script src="elasticlunr.min.js"></script>
        <script src="mark.min.js"></script>
        <script src="searcher.js"></script>
        <script src="clipboard.min.js"></script>
        <script src="highlight.js"></script>
        <script src="book.js"></script>

        <!-- Custom JS scripts -->
    </body>
</html>
